package com.xingge.sdktest;

import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jolimark.jetprinter.PrinterType;
import com.yingmei.ymsdk.WIFIPrint;
import com.yingmei.ymsdk.bean.CardInfo;
import com.yingmei.ymsdk.bean.PrintDataInfo;
import com.yingmei.ymsdk.bean.PrintDataType;
import com.yingmei.ymsdk.bean.ResultInfo;
import com.yingmei.ymsdk.callback.IReadResultCallback;
import com.yingmei.ymsdk.callback.PrintCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import androidx.appcompat.app.AppCompatActivity;

public class WiFiPrintActivity extends AppCompatActivity implements IReadResultCallback, PrintCallback {

    TextView tvInfo;
    EditText etIp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_print);
        tvInfo = findViewById(R.id.tv_info);
        etIp = findViewById(R.id.et_ip);
        WIFIPrint.setDebug(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WIFIPrint.destroy();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_init:
                String ip = etIp.getText().toString().trim();
                if (!TextUtils.isEmpty(ip)) {
                    WIFIPrint.initWifi(this, ip, this);
                }
                break;

            case R.id.bt_get_sn:
                WIFIPrint.getPrintSN(this, this);
                break;

            case R.id.bt_get_state:
                WIFIPrint.getPrintState(this, this);
                break;

            case R.id.bt_get_ml:
                WIFIPrint.inkjetCommand(this, PrintDataType.TYPE_READ_INK, this);
                break;

            case R.id.bt_print_img:
                toPicture();
                break;

            case R.id.bt_print_pdf:
                toPdf();
                break;

            default:
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                Uri uri = data.getData();
                String path = ImgUtils.getPath(this, uri);
                Log.d("xing", "path= " + path);
                if (path == null) {
                    tvInfo.setText("图片加载失败");
                    return;
                }
                PrintDataInfo printDataInfo = new PrintDataInfo(PrintDataType.TYPE_PRINT_IMG);
                printDataInfo.addFilePath(path);
                printDataInfo.colorType = 1;
                printDataInfo.qty = 1;
                printDataInfo.taskId = String.valueOf(System.currentTimeMillis());
                WIFIPrint.print(this, printDataInfo, this);
            } else if (requestCode == 101) {
                Uri uri = data.getData();
                if (uri == null) {
                    tvInfo.setText("文件加载失败");
                    return;
                }
                String path = uri.getPath();
                if (new File(path).exists()) {
                    PrintDataInfo printDataInfo1 = new PrintDataInfo(PrintDataType.TYPE_PRINT_PDF);
                    printDataInfo1.taskId = String.valueOf(System.currentTimeMillis());
                    printDataInfo1.qty = 1;
                    printDataInfo1.addFilePath(path);
                    WIFIPrint.print(this, printDataInfo1, this);
                } else {
                    checkUri(getContentResolver(), uri);
                }

            }
        }
    }

    private void toPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 100);
    }

    private void toPdf() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/pdf");
        startActivityForResult(intent, 101);
    }


    @Override
    public void onResult(CardInfo cardInfo) {
        tvInfo.setText(cardInfo.toString());
    }


    @Override
    public void printResult(PrinterType printerType, ResultInfo resultInfo) {
        if (resultInfo.printDataType == PrintDataType.TYPE_READ_INK) {
            tvInfo.setText("打印机墨量:" + resultInfo.result);
        } else if (resultInfo.printDataType == PrintDataType.TYPE_READ_SN) {
            tvInfo.setText(getPrintText(printerType) + "打印机SN:" + resultInfo.result);
        } else if (resultInfo.printDataType == PrintDataType.TYPE_PRINT_IMG) {
            tvInfo.setText(resultInfo.toString());
        } else if (resultInfo.printDataType == PrintDataType.TYPE_PRINT_PDF) {
            tvInfo.setText(resultInfo.toString());
        } else if (resultInfo.printDataType == PrintDataType.TYPE_PRINT_HTML) {
            tvInfo.setText(resultInfo.toString());
        } else {
            tvInfo.setText(resultInfo.toString());
        }
    }

    @Override
    public void onPrintState(PrinterType printerType, int state, String msg) {
        tvInfo.setText(getPrintText(printerType) + "打印机状态:" + msg);
    }

    @Override
    public void openState(PrinterType printerType, int state) {
        tvInfo.setText(getPrintText(printerType) + (state == 0 ? "连接成功" : "连接失败"));
    }

    private String getPrintText(PrinterType printerType) {
        return printerType == PrinterType.Ink ? "喷墨打印机" : "热敏打印机";
    }

    private void checkUri(ContentResolver contentResolver, Uri uri) {
        try {
            InputStream inputStream = contentResolver.openInputStream(uri);
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "print.pdf";
            new CopyFileThread(inputStream).execute(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    class CopyFileThread extends AsyncTask<String, Integer, String> {

        InputStream inputStream;

        public CopyFileThread(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String newPath = params[0];
            boolean b = copyFile(inputStream, newPath);
            if (b) {
                return newPath;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            PrintDataInfo printDataInfo1 = new PrintDataInfo(PrintDataType.TYPE_PRINT_PDF);
            printDataInfo1.taskId = String.valueOf(System.currentTimeMillis());
            printDataInfo1.qty = 1;
            printDataInfo1.addFilePath(s);
            WIFIPrint.print(WiFiPrintActivity.this, printDataInfo1, WiFiPrintActivity.this);

        }
    }

    public static boolean copyFile(InputStream inputStream, String newPath) {
        try {
            File destFile = new File(newPath);
            if (destFile.exists()) {
                // 如果目标文件存在并允许覆盖
                // 删除已经存在的目标文件，无论目标文件是目录还是单个文件
                destFile.delete();
            } else {
                // 如果目标文件所在目录不存在，则创建目录
                if (!destFile.getParentFile().exists()) {
                    // 目标文件所在目录不存在
                    if (!destFile.getParentFile().mkdirs()) {
                        return false;
                    }
                }
            }
            int byteread = 0;
            FileOutputStream fs = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024 * 100];
            while ((byteread = inputStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
            fs.flush();
            fs.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
